﻿<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Binary search</title>
    <link href="styles/js-console.css" rel="stylesheet" />
</head>
<body>
    <div id="js-console"></div>
	<script src="scripts/js-console.js"></script>
	<script>
	    var searchedElement = 40;
	    var arr = [4,2,5,7,3,2,-4,6,9,40,140];

        //Print the array:
	    for (var j = 0; j < arr.length; j++) {
	        jsConsole.write(arr[j] + " ");
	    }
	    function OrderBy(a, b) {
	        return (a == b) ? 0 : (a > b) ? 1 : -1
	    };

	    jsConsole.writeLine();
	    arr.sort(OrderBy)

        //Print sorted array:
	    for (var i = 0; i < arr.length; i++) {
	        jsConsole.write(arr[i] + " ");
	    }
	    jsConsole.writeLine();

	    //Binary search:
	    var min = 0;
	    var max = arr.length - 1;
	    var mid = 1;
	    while (max >= min) {
	        mid = Math.floor((min + max) / 2);
	        if (searchedElement == arr[mid]) {
	            jsConsole.writeLine("searched element '" + searchedElement +"' is found at position: " + mid);
	            break;
	        }
	       
	        if (searchedElement > arr[mid]){
	            min = mid + 1;
	        }
	        if (searchedElement < arr[mid]) {
	            max = mid - 1;
	        }
	    }
    </script>
</body>
</html>
